package chaoyue.study.lock;

import chaoyue.study.ThreadUtils;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 用于处理读多写少时的场景
 */
public class ReadAndWriteLockTest {
    public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public static int COUNT = 1;

    public static void main(String[] args) {
        // 读操作
        Runnable read = () -> {
            // 获取读锁并加锁
            ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
            readLock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " start: " + COUNT);
                ThreadUtils.sleep();
                System.out.println(Thread.currentThread().getName() + ": " + COUNT);
            } finally {
                readLock.unlock(); // 解锁
            }
        };

        //写操作
        Runnable write = () -> {
            // 获取写锁并加锁
            ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
            writeLock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " start: " + COUNT);
                ThreadUtils.sleep();
                COUNT++;
                System.out.println(Thread.currentThread().getName() + " end: " + COUNT);
            } finally {
                writeLock.unlock();// 解锁
            }
        };

        while (true) {
            Random random = new Random();
            // 生成随机数，来模拟读多写少的场景
            int flag = random.nextInt(100);
            if (flag > 20) {
                new Thread(read, "read").start();
            } else {
                new Thread(write, "write").start();
            }
        }
    }
}
